C++ - 如何解决函数重载歧义

标签 c++ c++11

考虑以下简单类(请不要争论有用性):

class Container
{
    public:
        Container(const long long &val); //construct the container with a long long
        Container(const long double &val); //construct the container with a long double
        Container(const std::string &val); //construct the container with a string
        Container(const Container &val); //copy constructor, implemented as copy and swap

        //explicit conversions are also included for other data types
        explicit operator long long() const; //explicit conversion to long long

    private:
        int dataType;
        void *data;
};

为了构建对象,我会调用:

Container cont(20); //or
Container cont2("some string");

但是编译器告诉我他无法解析对 int 的模糊构造函数调用。

这引出了我的问题,什么是解决这种歧义的最好和最干净的方法。
我应该使用某种看起来像这样的模板化构造函数吗:

Container<int> cont(20);

或者使用显式转换或虚拟参数?

模板化方式看起来像是我可以接受的折衷方案,但我确信实际调用看起来会有所不同。

谢谢您的任何见解!

最佳答案

只需为 int 添加一个构造函数来消除它的歧义:

Container(int i)
: Container(static_cast<long long>(i)) // or whichever version you want
                                       // to call
{ }

关于C++ - 如何解决函数重载歧义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31434420/

相关文章:

c++ - 基本 OpenGL 渲染的问题?

c++ - 是否有一个 GNU C 编译器选项可以生成运行速度比默认设置更快但精度更低的浮点程序?

c++ - 所有可写和可执行的程序内存段类型

c++ - MinGW、MinGW-w64 和 MinGW-builds 有什么区别?

c++ - C++11 中的 std::sin 变化?

c++ - 加快 g++ 编译时间

c++ - 访问命名空间中的枚举

c++ - 如何在多个类中使用相同的 unique_ptr

C++收集算法?

c++ - 在不违反严格别名规则的情况下,在现代 GCC/C++ 中使用网络缓冲区的正确方法