Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent bool to int conversion in constructor?

Tags:

c++

c++17

I have the following class, as close as possible to my production code:

#include <iostream>

template <typename T>
struct M {

    M(std::string a, std::string b, T value = T(), const bool ready = false) : m_value{value}, m_ready{ ready } {}

    T m_value;
    bool m_ready;

};

auto main() -> int {
    {
        M<int> m{"a", "b"};
        std::cerr << m.m_value << std::endl;
    }
    {
        M<int> m{"a", "b", true};
        std::cerr << m.m_value << std::endl;
    }
}

In the first instance the value of m_value is 0 as expected. In the second it's 1 since it's taking the value of bool. Is there a way to avoid the conversion?

like image 585
ruipacheco Avatar asked Feb 28 '20 14:02

ruipacheco


Video Answer


1 Answers

You can prevent the conversion by explicitly deleting a version that directly takes bool as the third parameter:

M(std::string, std::string, bool, bool = false) = delete;

However, if T is bool, that's going to cause problems. So you would need to use some SFINAE gymnastics to make this definition appear only when T is convertible to bool but isn't actually bool.

like image 142
Nicol Bolas Avatar answered Oct 05 '22 11:10

Nicol Bolas