还没有读过有关 C++ 模板的书,所以我遇到了一个问题。我正在使用 C++14。
如何根据类型本身将函数指针类型转换为特定的字符串? 我有函数指针类型:
using FuncType1 = int (*)(double);
using FuncType2 = int (*)(int);
using FuncType3 = int (*)(int);
我想写这样的东西:
class Test {
private:
template<FuncType1> static const std::string func_name = "FuncType1";
template<FuncType2> static const std::string func_name = "FuncType2";
template<FuncType3> static const std::string func_name = "FuncType3";
public:
template<T> std::string GetFuncType() {
return func_name<T>::value;
}
};
我知道这不能编译,但应该足以展示想法。我认为可以专门化 GetFuncType
方法,但我更愿意专门化成员变量 func_name
(如果可能的话)。此外 - 如果代码已修复,FuncType2 和 FuncType3 是否会解析为正确的字符串?
最佳答案
I would prefer to specialize member variable func_name instead (if that's even possible).
所以,如果我没理解错的话,你看起来像是
class Test
{
private:
template <typename> static const std::string func_name;
public:
template <typename T>
std::string GetFuncType () const
{ return func_name<T>; }
};
template <typename> const std::string Test::func_name = "not func";
template<> const std::string Test::func_name<FuncType1> = "FuncType1";
template<> const std::string Test::func_name<FuncType2> = "FuncType2";
template<> const std::string Test::func_name<FuncType3> = "FuncType3";
鉴于FuncType1
, FuncType2
和 FuncType3
是不同的类型(不等于 FuncType2
和 FuncType3
在你的问题)。
下面是一个完整的编译示例
#include <string>
#include <iostream>
using FuncType1 = int (*)(double);
using FuncType2 = int (*)(int);
using FuncType3 = int (*)(long);
class Test
{
private:
template <typename> static const std::string func_name;
public:
template <typename T>
std::string GetFuncType () const
{ return func_name<T>; }
};
template <typename> const std::string Test::func_name = "not func";
template<> const std::string Test::func_name<FuncType1> = "FuncType1";
template<> const std::string Test::func_name<FuncType2> = "FuncType2";
template<> const std::string Test::func_name<FuncType3> = "FuncType3";
int main ()
{
std::cout << Test{}.GetFuncType<int>() << std::endl;
std::cout << Test{}.GetFuncType<FuncType1>() << std::endl;
std::cout << Test{}.GetFuncType<FuncType2>() << std::endl;
std::cout << Test{}.GetFuncType<FuncType3>() << std::endl;
}
如果你想要Test{}.GetFuncType<int>()
给出编译错误,可以初始化func_name
仅适用于要求的特化
// template <typename> const std::string Test::func_name = "not func";
template<> const std::string Test::func_name<FuncType1> = "FuncType1";
template<> const std::string Test::func_name<FuncType2> = "FuncType2";
template<> const std::string Test::func_name<FuncType3> = "FuncType3";
// ...
std::cout << Test{}.GetFuncType<int>() << std::endl; // compilation error!
关于c++ - 将函数指针类型转换为对应的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57099553/