c++ - 强制编译时检查正确的对象实例化

标签 c++

如果用户错误地实例化某个类的对象,如何强制编译器给出错误?

例如:

Polynomial a("x^2 + 2x + 1"); //this is a valid Polynomial object

Polynomial b("3xy + 2 - 5/z"); //this is not valid, force compiler error

static_assert 似乎不适用于函数参数,模板似乎不适用于字符串。如果无法在编译时执行此操作,那么在运行时执行此操作的好方法是什么?

最佳答案

我确实阅读并阅读了您的问题和评论,也许我很困惑您想要什么,但为什么使用 constexpr 构造函数的简单解决方案不适合您:

#include <iostream>
struct Polynomial {
    const char* str;

    constexpr Polynomial(char const* arg) 
        : str(arg) {
        // if check fails when constructing constexpr Polynomial
        // we get compile error for throwing, otherwise works
        // if check fails when constructing runtime Polynomial
        // then it does throw
        if (arg[0] != 'b') throw 42; 
    }
};

int main() {
    // should compile as first character is 'b'
    constexpr Polynomial a("bar");
    const char* foo = "foo";
    try {
        // should throw as first character is not 'b'
        Polynomial b(foo);
    } catch (...) {
        std::cout << "Q.E.D." << std::endl;
    }
} 

这个 AFAIK 已经在 C++14 中工作了。

关于c++ - 强制编译时检查正确的对象实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70712181/

相关文章:

c++ - 为什么 GetExitCodeThread() 在这里返回 FALSE?

android - 如何在 Android 上打印堆栈跟踪(带有符号函数名称)?

c++ - 在 C++ 中使用线程调用方法

c++ - Boost.Thread 在 1.58 中醒来得太晚

c++ - Sprite 表动画期间闪烁

c++ - 使用 std::ios::ate 获取文件大小?

c++ - 似乎无法在 Boost 库中使用此功能

C++ 从 void* 转换为 SomeClass*

c++ - 如何给函数取其他名称?

c++ - 包括 std::forward 会产生错误,但它的遗漏会编译。为什么?