gpt4 book ai didi

c++ - VC++ 2013 : using-declaration + redefinition of member function leads to compile error

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:10:04 27 4
gpt4 key购买 nike

我想通过指定策略允许修改我的类的行为。该策略应该用作 boost::variant 的访问者。有适合大多数情况的默认策略,但用户可能需要添加或替换一些重载。

我发现 vc++ 2013 没有编译此代码并出现错误 C3066: There are multiple ways that an object of this type of can be called with these arguments。相同的代码在 gcc 和 clang 中按预期编译和工作。

是 vc++ 2013 的错误吗?

#include <iostream>

struct DefaultPolicy
{
void operator()( bool ) { std::cout << "Base: bool" << std::endl; }
void operator()( int ) { std::cout << "Base: int" << std::endl; }
};

struct UserModifiedPolicy : public DefaultPolicy
{
using DefaultPolicy::operator();
void operator()( int ) { std::cout << "Derived: int" << std::endl; }
void operator()( float ) { std::cout << "Derived: float" << std::endl; }
};

int main()
{
UserModifiedPolicy()(true);
UserModifiedPolicy()(1); // <-- ERROR HERE
UserModifiedPolicy()(1.f);
return 0;
}

UPD 这个例子适用于 vc++ 2010。看起来它是 2013 版本中的一个错误。


UPD 解决方法

#include <iostream>

struct DefaultPolicy
{
void operator()( bool ) { std::cout << "Base: bool" << std::endl; }
void operator()( int ) { std::cout << "Base: int" << std::endl; }
};

struct UserModifiedPolicy : public DefaultPolicy
{
// Using template to forward a call to the base class:
template< class T >
void operator()( T && t ) { DefaultPolicy::operator()( std::forward<T>(t) ); }

void operator()( int ) { std::cout << "Derived: int" << std::endl; }
void operator()( float ) { std::cout << "Derived: float" << std::endl; }
};

int main()
{
UserModifiedPolicy()(true);
UserModifiedPolicy()(1);
UserModifiedPolicy()(1.f);
return 0;
}

最佳答案

代码格式正确。 7.3.3/15:

When a using-declaration brings names from a base class into a derived class scope, member functions and member function templates in the derived class override and/or hide member functions and member function templates with the same name, parameter-type-list (8.3.5), cv-qualification, and ref-qualifier (if any) in a base class (rather than conflicting).

所以 UserModifiedPolicy::operator()(int) 应该仍然隐藏 DefaultPolicy::operator()(int)operator() 的名称查找应该找到三个成员 DefaultPolicy::operator()(bool)UserModifiedPolicy::operator()(int)UserModifiedPolicy::operator()(float)

关于c++ - VC++ 2013 : using-declaration + redefinition of member function leads to compile error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24409307/

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