C++ - 专用化类模板的成员函数
C++ - specialize class template's member function
我正在寻找有关模板的帮助。我需要在模板中创建对特定类型有不同反应的函数。
它可能看起来像这样:
template <typename T>
class SMTH
{
void add() {...} // this will be used if specific function isn't implemented
void add<int> {...} // and here is specific code for int
};
我还尝试在单个函数中通过类型使用typeid
和swich
,但对我不起作用
您真的不想在运行时使用typeid
进行这种分支。
我们想要这个代码:
int main()
{
SMTH<int>().add();
SMTH<char>().add();
return 0;
}
输出:
int
not int
我可以想出很多方法来实现这一点(全部在编译时,其中一半需要C++11):
专门化整个类(如果它只有这个
add
函数):template <typename T> struct SMTH { void add() { std::cout << "not int" << std::endl; } }; template <> struct SMTH<int> { void add() { std::cout << "int" << std::endl; }; };
仅专门化
add
成员函数(由@Angelus推荐):template <typename T> struct SMTH { void add() { std::cout << "not int" << std::endl; } }; template <> // must be an explicit (full) specialization though void SMTH<int>::add() { std::cout << "int" << std::endl; }
注意,如果您使用cv限定的int
实例化SMTH
,您将获得上述方法的not int
输出。
使用SFINAE习语它有几种变体(默认模板参数、默认函数参数、函数返回类型),最后一种是适合这里的:
template <typename T> struct SMTH { template <typename U = T> typename std::enable_if<!std::is_same<U, int>::value>::type // return type add() { std::cout << "not int" << std::endl; } template <typename U = T> typename std::enable_if<std::is_same<U, int>::value>::type add() { std::cout << "int" << std::endl; } };
主要的好处是,您可以使启用条件变得复杂,例如使用
std::remove_cv
来选择相同的重载,而不考虑cv限定符。标记调度-根据实例化的标记是否继承自
A
或B
(在本例中为std::false_type
或std::true_type
)来选择add_impl
过载。您仍然使用模板专业化或SFINAE,但这次是在标签类上完成的:template <typename> struct is_int : std::false_type {}; // template specialization again, you can use SFINAE, too! template <> struct is_int<int> : std::true_type {}; template <typename T> struct SMTH { void add() { add_impl(is_int<T>()); } private: void add_impl(std::false_type) { std::cout << "not int" << std::endl; } void add_impl(std::true_type) { std::cout << "int" << std::endl; } };
当然,这可以在不定义自定义标记类的情况下完成,
add
中的代码如下所示:add_impl(std::is_same<T, int>());
我不知道我是否都提到了,也不知道我为什么要这么做。您现在所要做的就是选择最适合使用的。
现在,我看到了,你还想检查一个函数是否存在。这已经很长了,而且已经有一个QA了。
相关文章:
- 对RValue对象调用的LValue ref限定成员函数
- 为什么使用 "this" 指针调用派生成员函数?
- 将公共但非静态的成员函数与ALGLIB集成
- 使用指向成员的指针将成员函数作为参数传递
- 将重载的成员函数传递给函数模板
- 我不小心调用了一个没有自己类对象的成员函数.但这是怎么回事呢
- 如何在C++中使用非静态成员函数作为回调函数
- C++错误C2600:无法定义编译器生成的特殊成员函数(必须首先在类中声明)
- 关联容器的下界复杂性:成员函数与非成员函数
- 在 C++ 中用派生类型重写成员函数
- 链表的泛型函数remove()与成员函数remove)
- 如何将lambda作为模板类的成员函数参数
- constexpr构造函数需要常量成员函数时出现问题
- 将自由函数绑定为类成员函数
- 区分非成员函数和头文件中的成员函数
- 如何从子成员函数修改父公共成员变量
- 保留对其他类的成员函数的引用
- 在运算符重载定义中使用成员函数(const错误)
- 内联如何影响模块接口中的成员函数
- 将成员函数指针作为参数传递给模板方法