Violet Giraffe
Violet Giraffe

Reputation: 33589

Unsuccessful attempt at using tag dispatching: "cannot convert from bool to std::true_type"

#include <iostream>
#include <type_traits>

template <bool b>
struct Conditional
{
    void f()
    {
        fImpl(b);
    }

private:
    void fImpl(std::true_type)
    {
        std::cout << "true";
    }

    void fImpl(std::false_type)
    {
        std::cout << "false";
    }
};

void main()
{
    Conditional<true>().f();
}

The code above produces the error:

cannot convert argument 1 from 'bool' to 'std::true_type'

I don't understand why it happens and what I'm doing wrong. I've used this trick in the past with no problem.

Upvotes: 4

Views: 606

Answers (1)

Pradhan
Pradhan

Reputation: 16737

You can't have an implicit conversion based on the value of whatever's being converted. Given that b is a template bool argument, you can do

void f()
{
    fImpl(std::integral_constant<bool, b>());
}

Upvotes: 4

Related Questions