gpt4 book ai didi

c++ - 显式模板特化不能有存储类 - 成员方法特化

转载 作者:搜寻专家 更新时间:2023-10-31 00:12:51 26 4
gpt4 key购买 nike

假设我在 Visual Studio 中有以下代码

class foo
{
public:
template<typename t>
void foo_temp(int a , t s_)
{
std::cout << "This is general tmeplate method";
}

template<>
static void foo_temp(int a , int s)
{
std::cout << "This is a specialized method";
}
};


int main()
{
foo f;
f.foo_temp<std::string>(12,"string");
}

现在我正试图将其转换为 GCC。通过 SO 上的其他问题,我注意到在 GCC 中,如果类不是专门的,则成员方法不能专门化。因此我想出了这个解决方案

class foo
{

public:
template<typename t>
void foo_temp(int a , t s_)
{
std::cout << "This is general template method";
}


};

template <>
/*static*/ void foo::foo_temp<int>(int a, int value) {
std::cout << "Hello world";
}

现在这似乎可以解决问题,但是当我将 static 关键字包含到语句中时,我得到了错误

 explicit template specialization cannot have a storage class

现在this线程谈论它,但我仍然对如何在这里应用它感到困惑。关于如何使最后一个方法静态的任何建议?此外,我仍然对为什么模板化方法在 GCC 中不能是静态的感到困惑?

这是 Visual Studio Code

class foo
{
public:
template<typename t>
void foo_temp(int a , t s_)
{
std::cout << "This is general tmeplate method";
}

template<>
static void foo_temp(int a , int s)
{
std::cout << "This is a specialized method";
}
};


int main()
{
foo f;
f.foo_temp<std::string>(12,"string");
}

最佳答案

Any suggestions on how I can make the last method static?

你不能;语言不支持它。

Also I am still confused as to why templated methods cant be static in GCC?

他们可以;它们不能既是静态的又是非静态的。示例:

struct foo {
template<typename T>
void bar() {}

template<typename T>
static void baz() {}
};

int main() {
foo f;
f.template bar<void>();
foo::baz<void>();
}

我很困惑为什么必须对(非静态)模板成员函数进行静态特化。我会认真地重新评估这段代码的完整性。

请注意,对于评论中的问题,不可能对静态成员函数进行模板特化,因为在这种情况下根本不可能对成员函数进行模板特化。 (改用重载。)

struct foo {
template<typename T, typename U>
static void bar(T, U) {}

// Error, you'd need to also specialize the class, which requires a template class, we don't have one.
// template<>
// static void bar(int, int) {}
// test.cpp:2:12: error: explicit specialization of non-template ‘foo’
// 2 | struct foo {
// | ^

// Partial specializations aren't allowed even in situations where full ones are
// template<typename U>
// static void bar<int, U>(int, U) {}
// test.cpp:14:33: error: non-class, non-variable partial specialization ‘bar<int, U>’ is not allowed
// 14 | static void bar<int, U>(int, U) {}
// | ^

// Instead just overload
template<typename U>
static void bar(int, U) {}
};

关于c++ - 显式模板特化不能有存储类 - 成员方法特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29041775/

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