Jar*_*a M 4 c++ templates specialization
我正在寻找模板的帮助.我需要在模板中创建对特定类型有不同反应的函数.
它可能看起来像这样:
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
};
Run Code Online (Sandbox Code Playgroud)
我也尝试在单个函数中使用typeid和swich通过类型,但对我不起作用.
你真的不想在运行时进行这种分支typeid.
我们想要这个代码:
int main()
{
SMTH<int>().add();
SMTH<char>().add();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
要输出:
int
not int
Run Code Online (Sandbox Code Playgroud)
有很多方法可以实现这一点(所有这些都在编译时,其中一半需要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; };
};
Run Code Online (Sandbox Code Playgroud)仅专注于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; }
Run Code Online (Sandbox Code Playgroud)请注意,如果SMTH使用cv-qualified进行实例化int,您将获得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; }
};
Run Code Online (Sandbox Code Playgroud)
主要的好处是你可以使启用条件复杂化,例如使用std::remove_cv选择相同的过载而不管cv限定符.
标签分派 - add_impl根据实例化标签是否继承A或选择过载B,在这种情况下std::false_type或std::true_type.您仍然使用模板特化或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; }
};
Run Code Online (Sandbox Code Playgroud)
这当然可以在不定义自定义标记类的情况下完成,代码add将如下所示:
add_impl(std::is_same<T, int>());
Run Code Online (Sandbox Code Playgroud)我不知道我是否全部提到它们,我也不知道为什么我会这样做.您现在要做的就是选择最适合使用的那个.
现在,我明白了,你也想检查一个函数是否存在.这已经很久了,现在有一个关于这个问题的质量保证.
| 归档时间: |
|
| 查看次数: |
197 次 |
| 最近记录: |