gpt4 book ai didi

c++ - 带有模板化参数函数的模板化成员变量上的错误 C2244,仅发生在 Visual Studio 上

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:29:11 26 4
gpt4 key购买 nike

我在 Visual Studio 上遇到了一个有趣但非常烦人的错误,下面是最简单的重现:(取消注释 #define 将允许 VS 构建代码)

#include <iostream>
using namespace std;

//#define BUILD_ON_VS

class CC
{
public:
template<typename T>
struct Foo
{
template<T foo>
void bar()
{
cout << "VC likes this!\n";
}
#ifndef BUILD_ON_VS
template<T foo>
void bar1();
#endif
};

Foo<int> m_foo;
};

#ifndef BUILD_ON_VS
template<typename T>
template<T foo>
void CC::Foo<T>::bar1()
{
cout << "VC doesn't like this...\n";
}
#endif

int main()
{
CC cc;
cc.m_foo.bar<-1>();
#ifndef BUILD_ON_VS
cc.m_foo.bar1<2>();
#endif
return 0;
}

基本上,我不能将函数 bar 的定义放在 Visual Studio 中的类之外。 bar 和 bar1 在其他方面完全相同。在 VS 2010 和 VS 2012 上测试,均因错误而失败:

error C2244: 'CC::Foo<T>::bar1' : unable to match function definition to an existing declaration
definition
'void CC::Foo<T>::bar1(void)'
existing declarations
'void CC::Foo<T>::bar1(void

然而,它适用于所有在线编译器,例如 compileonline 和 ideone。

我想将所有内容都保留在 cpp 文件中,而不是在 .h 中,以保持代码库干净。

Setting var1 to:
{
template<typename TT, TT foo>
void bar1();
}

template<typename T>
template<typename TT, TT foo>
void CC::Foo<T>::bar1()
{
}

也有效,但它通过重新定义相同的模板参数使代码看起来很愚蠢,并且更容易出现错误。它还使界面变得困惑。

最佳答案

通过随机输入找到一个修复程序,看看它是否编译,哈哈!!!看起来有点傻...

#include <iostream>
using namespace std;

//#define BUILD_ON_VS

class CC
{
public:

template<typename T>
struct Foo;

Foo<int>* m_foo;

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

template<typename T>
template<T foo>
void CC::Foo<T>::bar()
{
cout << "VC happen to like this...\n";
}

int main()
{
CC cc;
cc.m_foo = new CC::Foo<int>;
cc.m_foo->bar<2>();
}

我需要创建一个抽象类并用模板参数实例化它;

想知道为什么 VC 不能像 GCC 那样自动执行此操作。

关于c++ - 带有模板化参数函数的模板化成员变量上的错误 C2244,仅发生在 Visual Studio 上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14631554/

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