可以在类模板中专门用于类模板之外的模板函数吗?

时间:2014-04-04 20:58:50

标签: c++ templates

可以在类模板中专门设置的类模板中的模板函数吗? 它的语法是什么?

以下代码在MSVC2010中提供unable to match function definition to an existing declaration

#include <iostream>

template <typename T>
struct Test
{
    template <typename S>
    void test(const S & t);

    //this works
    //template<> void test(const double & t) { std::cout << t << "D \n"; }

    T member;
};

//this doesn't work
template <typename T>
template <>
void Test<T>::test(const double & t)
{
    std::cout << t << "D \n";
}

int main()
{
    Test<int> t;
    t.test(7.0);
}

修改

我可以按照答案中的建议使用重载,因为我使用它的方式略有不同,以下是:

#include <iostream>

template <typename T>
struct Test
{
    template <typename S>
    void test() { std::cout << "Any type \n"; }

    template <>
    void test<double>() { std::cout << "Double! \n"; }

    T member;
};

int main()
{
    Test<int> t1;
    Test<int> t2;
    t1.test<float>();
    t2.test<double>();
}

我希望在struct之外的双重专精。

为什么我这样使用它?在实际场景中,我已经构建了工厂类,使用如下:

Factory<SomePolicy> f;
f.create<MyType>(arg1, arg2, ...)

我需要对create的特殊类型进行专门化,以防止污染头文件。

2 个答案:

答案 0 :(得分:0)

我不相信你可以专注于内部模板而不专门化外部。但是,您可以使用部分专业化:

编辑:似乎只有类可以部分专业化。我再也没有测试过它。您可以找到更多here

template <typename T, typename S>
struct Test 
{
   void test(const S &s);
};

template <typename T>
struct Test<T, float>
{
   void test (const float &s)
   {
      <<do something>>
   }
}

答案 1 :(得分:0)

据我所知你不能。但是您可以像这样重载test函数:

template <typename T>
struct Test
{
    template <typename S>
    void test(const S & t);

    void test(const double &); // <-- Add this

    T member;
};

template <typename T> 
// template<> // <-- Remove this
void Test<T>::test(const double & t)
{
    std::cout << t << "D \n";
}

这应该完全等同于你想要做的事情。

相关问题