C++ 模板函数特化

标签 c++ templates specialization

我必须为定义如下的模板类实现一个非成员函数 isHomogenous(Triple triple):

template <typename T1, typename T2, typename T3>
    class Triple
{
public:
    Triple()
    { }
    Triple(const T1 &a, const T2 &b, const T3 &c) : a(a), b(b), c(c)
    { }
...

isHomogenous 函数应该返回一个 bool 值,指示参数三元组中的所有三个值是否都属于同一类型。我试过:

template <typename T> bool isHomogenous(Triple<T, T, T> triple) {
    return true;
}

template <typename T1, typename T2, typename T3> bool isHomogenous(Triple<T1, T2, T3> triple) {
    return false;
}

这行不通,你能给我一个解决方案吗?

最佳答案

函数模板不能部分特化。

一种替代方法是将其定义为类模板的静态成员函数(或者在您的情况下只是一个值!),然后只提供一个普通的函数模板包装器,例如......

#include <type_traits>

template< class T1, class T2, class T3 >
struct Blah {};

namespace detail {
    template< class T1, class T2, class T3 >
    struct IsHomogenous { static bool const yes = false; };

    template< class T >
    struct IsHomogenous< T, T, T > { static bool const yes = true; };
}  // namespace detail

template< class T1, class T2, class T3 >
bool isHomogenous( Blah< T1, T2, T3 > )
{
    return detail::IsHomogenous< T1, T2, T3 >::yes;
}

#include <iostream>
int main()
{
    using namespace std;
    wcout << boolalpha
        << isHomogenous( Blah< double, char, void >() ) << " "
        << isHomogenous( Blah< int, int, int >() )
        << endl;
}

另一种方法是使用 C++11 std::is_same:

#include <type_traits>

template< class T1, class T2, class T3 >
struct Blah {};

template< class T1, class T2, class T3 >
bool isHomogenous( Blah< T1, T2, T3 > )
{
    using std::is_same;
    return is_same< T1, T2 >::value && is_same< T2, T3 >::value;
}

#include <iostream>
int main()
{
    using namespace std;
    wcout << boolalpha
        << isHomogenous( Blah< double, char, void >() ) << " "
        << isHomogenous( Blah< int, int, int >() )
        << endl;
}

关于C++ 模板函数特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12893411/

相关文章:

c++ - 在 C++ 中按降序打印 map 值

c++ - vector 类 C++ 的 pop_back 和删除

c++ - 需要一个从 vector 派生的 vector

C++ - 在具有非类型模板参数的模板化类上专门化函数模板

rust - 是否可以专注于静态生命周期?

新婴儿贺卡的 C++ 代码片段

c++ 在遍历所有迭代器时删除 std::vector.end()

c++ - 使用静态函数变量与类变量来存储一些状态

c++ - 为什么必须在何处以及为什么要放置"template"和"typename"关键字?

php - 网站多页 |模板 |搜索