标签: if-constexpr

使用constexpr验证构造函数中的文字参数

我开始尝试constexpr.
我想要实现的是验证literal作为ctor参数提供的数值.
我开始使用以下内容,如果构造MyStruct 值<= 4 则抛出.

constexpr int validate(int v)
{
  return (v > 4) ? v : throw exception();
};

struct MyStruct final
{
  constexpr MyStruct(const int v)
    : _v{validate(v)}
  {
  }

  void add(int toAdd)
  {
    _v += toAdd;
  }

  int _v;
};

int main(int argc, char**)
{
  constexpr MyStruct a{500};  // ok so far...
  a.add(argc);                // ...nope 
  MyStruct b{500};            // check at runtime :(
  MyStruct c{argc};           // runtime check ok
}
Run Code Online (Sandbox Code Playgroud)

标记MyStruct …

c++ validation constexpr c++17 if-constexpr

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

constexpr静态成员什么时候停止成为constexpr?

我有这个片段.

#include <iostream>
#include <string>

struct JustStr {
    JustStr(const std::string& x) : val(x) {}
    static constexpr bool pred = false;
    std::string val;
};

template <typename T>
class C {
 private:
    T x;
 public:
    C(T x_) : x(x_) {}
    void f() {
        if constexpr (!x.pred) {
                std::cout << x.val << std::endl;
            }
    }

};

template<typename T>
void f2(T x) {
    T y(x);
    if constexpr (!y.pred) {
            std::cout << x.val << std::endl;
        }
}

int main() {
    C<JustStr> c(JustStr("yes"));
    c.f();  // Fails …
Run Code Online (Sandbox Code Playgroud)

c++ constexpr c++17 if-constexpr

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

使用constexpr-if时出错:预期'(''constexpr'之前'

我试图使用if-constexpr检查一些东西,但我遇到了类似的错误

预期'('之前'constexpr'

没有先前'if'的'else'

到目前为止,我检查我的代码没有任何问题

我的编译标志是g ++ -std = c ++ 17 main.cpp

#include <iostream>
template<typename T, typename Comp = std::less<T> >
struct Facility
{
template<T ... list>
struct List
{
    static void print()
    {
        std::cout<<"\""<<"Empty List"<<"\""<<"\n";
    }
};
template<T head,T ... list>
struct List<head,list...>
{
    static void print()
    {
        std::cout<<"\"" << head;
        ((std::cout << " " << list), ...);
        std::cout<<"\""<<"\n";
    }
};
template<unsigned N,typename AA>
struct RemoveFirst{};

template<unsigned N,T head,T ... Rest>
struct RemoveFirst<N,List<head,Rest...>>
{
    struct result
    {
        static void …
Run Code Online (Sandbox Code Playgroud)

c++ c++17 if-constexpr

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

如果vs constexpr里面的constexpr函数

最近,我修改了一些if constexprif我constexpr功能,发现他们仍然正常工作,并能进行评估时,编译时间.这是一个最小的案例:

template<int N>
constexpr bool is_negative()
{
    if constexpr  (N >= 0) return false;
    else  return true; 
}
int main()
{
    constexpr  bool v = is_negative<1>();
}
Run Code Online (Sandbox Code Playgroud)

live demo

在上面的例子中,N必须在编译时知道因为它是非类型模板参数,所以if constexpr在这里工作正常.然而,这是一个constexpr功能,因此,IIRC,它是可以让即使我更换一个返回值if constexprif:

template<int N>
constexpr bool is_negative()
{
    if  (N >= 0) return false;
    else  return true; 
}
int main()
{
    constexpr  bool v = is_negative<1>();
}
Run Code Online (Sandbox Code Playgroud)

live demo

cppref来看,所有的要求A constexpr function …

c++ compile-time constexpr if-constexpr

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

如果constexpr vs如果常量

如这个问题所示:link,如果两个if分支都有效,则两者之间没有区别:

const int foo = 5;
if (foo == 5)
{
    ...
}
else 
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

const int foo = 5;
if constexpr (foo == 5)
{
    ...
}
else 
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

在优化方面(在两种情况下else都不会实例化分支)。因此,如果if可以在编译时检查vanilla中的表达式(它涉及到constconstexpr),那么优化也可以在此处进行。

我以前认为这是的目的if constexpr,但我错了。那么,除了用例之外,还有没有if constexpr其他用例,那么我们可能只有许多if分支有效之一?

c++ optimization constexpr if-constexpr

3
推荐指数
2
解决办法
89
查看次数

从什么意义上说std :: disjunction在compile_time短路

cppreference.com上的描述中,我得到的印象是std :: disjunction旨在使我在编译时短路,因此我可以这样使用它:

#include <type_traits>
#include <iostream>

template<nullptr_t null = nullptr>
constexpr bool does_not_compile() {
    static_assert(null != nullptr);
    return false;
}

void hello_world () {
    if constexpr (std::disjunction_v<std::true_type, std::bool_constant<does_not_compile()>>) {
        std::cout << "Hello World!" << std::endl;
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,这不会编译,在上述static_assert不会触发的意义上,std :: disjunction不会短路(实时示例)。

但是,那是什么意思呢?这不是||的通常行为 在运行时,因为必须在编译时知道std :: disjunction的类型,这取决于其值。

c++ std variadic-templates c++17 if-constexpr

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

if constexpr 块未编译

我有一个类,可以从空结构或具有某些成员的结构继承,具体取决于bool. 使用相同的方法bool,我添加一个if constexpr块来访问基类的成员,但出现编译器错误

struct A{};
struct B{};
struct C{};

template <typename J0, typename J1>
struct HasFriction {
    constexpr static bool value = false;
};

template <> struct HasFriction<A,B> {
    constexpr static bool value = true;
};

template <bool> struct Friction { };
template <> struct Friction<true> { int value = 4; };

template <typename J0, typename J1>
struct MyStruct : public Friction<HasFriction<J0, J1>::value> {};

int main()
{
    if constexpr (HasFriction<A, C>::value) {
        MyStruct<A,C> f; …
Run Code Online (Sandbox Code Playgroud)

c++ templates template-meta-programming c++17 if-constexpr

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

折叠表达式中的“if constexpr”

我正在尝试在函数中创建一个折叠表达式,该函数用来自字符串向量的一些值填充函数的传出参数。我的折叠表达式是这样的:

  ((if constexpr (std::is_integral_v<Args>)
  {
      args = std::stoi(vec[index++]);
  }
  else if constexpr (std::is_same_v<Args, std::string>)
  {
      args = vec[index++];
  }
  else
  {
      throw std::invalid_argument("Unsupported argument type.");
  }), ...);
Run Code Online (Sandbox Code Playgroud)

但它无法编译并出现奇怪的错误消息:

clang: error: expected expression
Run Code Online (Sandbox Code Playgroud)

或者

gcc: error: expected primary-expression before 'if'
Run Code Online (Sandbox Code Playgroud)

(如https://gcc.godbolt.org/z/xeq3j6oE7所示)

有人提示如何正确解决此问题吗?

编辑

这个问题的完整背景是这个简短的应用程序:

#include <vector>
#include <string>
#include <type_traits>
#include <iostream>
#include <stdexcept>
template <typename... Args>
void populateArgs(std::vector<std::string>& vec, Args&... args)
{
    const size_t numArgs = sizeof...(Args);
    if (vec.size() != numArgs)
    {
        throw std::invalid_argument("Number of arguments doesn't match the …
Run Code Online (Sandbox Code Playgroud)

c++ templates fold-expression c++17 if-constexpr

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

与 std::stof 相比,编写通用的 string_to_float&lt;T&gt; 没有任何开销

我想编写一个string_to_float带有模板参数的函数,T分别满足、和、when和。我的尝试如下:string_to_float = std::stofstring_to_float = std::stodstring_to_float = std::stoldT = floatT = doubleT = long double

template<typename T>
T string_to_float(std::string const& s, std::size_t* pos = nullptr)
{
    static_assert(std::is_same_v<T, float> || std::is_same_v<T, double> || std::is_same_v<T, long double>,
        "T is not a built-in floating point type");

    if constexpr (std::is_same_v<T, float>)
        return std::stof(s, pos);
    if constexpr (std::is_same_v<T, double>)
        return std::stod(s, pos);
    if constexpr (std::is_same_v<T, long double>)
        return std::stold(s, pos);

    return T{};
}
Run Code Online (Sandbox Code Playgroud)

不过,我对这个return声明感到担忧。虽然在这种情况下静态断言已经失败,但我不想在 …

c++ c++20 if-constexpr c++-attributes

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

对'if constexpr'的理解有误

我有以下代码

static constexpr bool condition = true;

int square(int num) {
    if constexpr (condition) {
      return num * num;
    } else {
      x
      return num;
    }
}

int main() {
    return square(3);
}
Run Code Online (Sandbox Code Playgroud)

用编译

-std = gnu ++ 17

我的假设

if constexpr (condition)
Run Code Online (Sandbox Code Playgroud)

是在编译过程中

    } else {
      x
      return num;
    }
Run Code Online (Sandbox Code Playgroud)

被丢弃,我没有得到关于未定义的错误

X

我的理解是错误的,这个“如果constexpr”是这样的

#ifdef CONDITION
  return num * num;
#else
  x
  return num;
#endif
Run Code Online (Sandbox Code Playgroud)

如何修改此代码以进行编译?

谢谢您的帮助

c++ c++17 if-constexpr

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