gpt4 book ai didi

c++ - 类模板中的模板函数可以在类模板之外专门化吗?

转载 作者:太空狗 更新时间:2023-10-29 23:16:37 25 4
gpt4 key购买 nike

类模板内的模板函数可以在类模板外特化吗?它的语法是什么?

以下代码在 MSVC2010 中给出无法将函数定义与现有声明相匹配

#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 之外专门化 double。

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

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

我需要为不会污染头文件的特定类型专门化 create

最佳答案

据我所知你不能。但是你可以像这样重载你的 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";
}

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

关于c++ - 类模板中的模板函数可以在类模板之外专门化吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22872892/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com