小编flo*_*eng的帖子

为什么 const 指针会意外转换为 bool?

我有一个带有两个构造函数的类。一为bool一为A*

struct B
{
    explicit B(bool b)
    {
      std::cout << "B(bool)" << std::endl;
    }
    explicit B(A*)
    {
      std::cout << "B(A*)" << std::endl;
    }
};
Run Code Online (Sandbox Code Playgroud)

当 B 应该用const A*而不是A*-构造时,const A*将转换为bool.

const A a;
B b(&a);
Run Code Online (Sandbox Code Playgroud)

输出: B(bool)


所需的解决方案是

编译器错误:“B(const A*) 没有有效的构造函数”

我已经尝试过使用explicit关键字,但是没有用。

在coliru运行示例

c++ casting compiler-errors boolean-expression

3
推荐指数
1
解决办法
134
查看次数

非模板类的构造函数中的模板参数

我想要一个非模板类的构造函数,它由一个类型模板化.有人可以帮忙吗?

class A
{
    public:
    static int GetId(){ return 5;}
};

class B
{
    public:
    B(int id){ _id = id;}

    template<typename T> 
    B() {_id = T::GetId();}

    template<typename T>
    static B* newB() {return new B(T::GetId());}

    private:
    int _id;
};

void doSome()
{
    B* p1 = B::newB<A>(); //works
    B* p2 = new B<A>(); //doesn't compile -- ">>B<< is no template"
}
Run Code Online (Sandbox Code Playgroud)

c++ templates

2
推荐指数
1
解决办法
666
查看次数