Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

templates

#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.

like image 310
Violet Giraffe Avatar asked Oct 21 '25 23:10

Violet Giraffe


1 Answers

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>());
}
like image 118
Pradhan Avatar answered Oct 24 '25 14:10

Pradhan