Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
497 views
in Technique[技术] by (71.8m points)

templates - if / else at compile time in C++?

Consider the following code :

#include <iostream>
#include <type_traits>

template<typename T> class MyClass
{
    public:
        MyClass() : myVar{0} {;}
        void testIf() {
            if (isconst) {
                myVar;
            } else {
                myVar = 3;
            }
        }
        void testTernary() {
            (isconst) ? (myVar) : (myVar = 3);
        }

    protected:
        static const bool isconst = std::is_const<T>::value;
        T myVar;
};

int main()
{
    MyClass<double> x;
    MyClass<const double> y;
    x.testIf();
    x.testTernary();
    y.testIf(); // <- ERROR
    y.testTernary(); // <- ERROR
    return 0;
}

For x (non-const) there is no problem. But y (const data type) cause an error even if the condition in if/else is known at compile-time.

Is there any possibility to not compile the false condition at compile-time ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

C++17 if constexpr

Oh yes, it has arrived:

main.cpp

#include <cassert>
#include <type_traits>

template<typename T>
class MyClass {
    public:
        MyClass() : myVar{0} {}
        void modifyIfNotConst() {
            if constexpr(!isconst) {
                myVar = 1;
            }
        }
        T myVar;

    protected:
        static constexpr bool isconst = std::is_const<T>::value;
};

int main() {
    MyClass<double> x;
    MyClass<const double> y;
    x.modifyIfNotConst();
    y.modifyIfNotConst();
    assert(x.myVar == 1);
    assert(y.myVar == 0);
    return 0;
}

GitHub upstream.

Compile and run:

g++-8 -std=c++17 -Wall -Wextra -pedantic -o main.out main.cpp
./main.out

See also: Difference between "if constexpr()" Vs "if()"

This will be really cool together with C++20 "string literal template arguments": Passing a string literal as a parameter to a C++ template class

Tested in Ubuntu 16.04, GCC 8.1.0.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...